// pages/entry/index.js
import { removeObj } from '../../utils/removeObj.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // totalPrice:0,//总价
    showviewstate: false, //是否显示组别遮罩层
    select: -1, //当前选择的下标 不等于-1 的时候代表已选择
    bindIndex: -1, // 点击去修改或者去补充时用户的下标
    payState:false, // 是否可支付
    matchSkuList:[],//赛事组别 动态表单添加到里面
    groupValue:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2]; //当前页
    let data = prevPage.data;
    data.shortAddress = data.shortAddress.replace(/\,/g, ' | ')
    data.day = data.showTimeStart.replace(/\./g, '-')
    let num = ''
    switch (new Date(data.day).getDay()) {
      case 1:
        num = '一';
        break;
      case 2:
        num = '二';
        break;
      case 3:
        num = '三';
        break;
      case 4:
        num = '四';
        break;
      case 5:
        num = '五';
        break;
      case 6:
        num = '六';
        break;
      default:
        num = '日';
        break;
    }
    data.showWeek = '周' + num
    this.setData({
      ...removeObj(data, ['searchEnroll','__webviewId__','searchResult','image', 'recommendIds', 'openNavList', 'total', 'isRequst', 'status', 'minPrice', 'timeEnd','imgDraw','registTime', 'deadlineRegist', 'timeStart', 'currentTab', 'btnText', 'sharePath', 'qrCode'])}) //取上页data里的数据也可以修改
  },
  //确认别组
  toPay() {
    let { matchSkuList, select, groupValue} = this.data
    if (select > -1) {
      let matchSku = matchSkuList[select];//对应组别数据
      // console.log(matchSku.qulificateIds)
      let {skuNum,skuType,limitNum,selectedUser,qulificateIds,matchSkuFormList} = matchSku
        if (skuNum == 0) {
          this.showToast('当前组别参赛人数已满')
        }else if (!matchSku.hasOwnProperty('selectedUser')) {
          this.showToast('请选择参赛人员')
        } else if (skuType == 2 && groupValue == '') {
          this.showToast('请填写团队名称')
        } else if (skuType == 2 && limitNum != selectedUser.length) {
          this.showToast(`当前人数：${selectedUser.length}人，团队人数应为：${limitNum}人`,'none',2000)
        } else {
          let errUserTitle = ''; // 存用户信息错误提示
          if(qulificateIds){
            let mustAns = matchSkuFormList.length>0&&matchSkuFormList.findIndex((value)=>value.required==1)!=-1; // 表单是否有必填项
            console.log(mustAns)
            selectedUser.forEach((e, i) => {
              if (errUserTitle == '') { // 没有报错信息
                if (!mustAns && e.hasSkuQualificate == 1) {//不需要填和资质认证成功
    
                } else if (e.hasSkuQualificate != 8 && e.hasSkuQualificate != 9) {
                  errUserTitle = `请检查${matchSku.selectedUser.length > 1 ? '【第' + Number(i + 1)+'位】':''}【${e.name}】表单信息`
                }
              }
            });
          }
          if (errUserTitle != '') {
            this.showToast(errUserTitle)
          } else {
            wx.navigateTo({url: '/pages/entry/index'})
          }
        }
    } else {
      this.showToast('请选择别组')
    }
  },
  editData(e) {
    let {index} = e.currentTarget.dataset;
    this.setData({ bindIndex: index })
    let {matchSkuList,select} = this.data;
    let matchSku =matchSkuList[select];
    let u = matchSku.selectedUser[index]
    let name = matchSku.qualificateList.length==0?'':'&title='+matchSku.qualificateList[0].name;
    let remark = matchSku.qualificateList.length==0?'':'&remark='+matchSku.qualificateList[0].remark;
    wx.navigateTo({
      url: `/pages/qualification_supplement/index?barTitle=完善信息&pid=${u.participantId}&userName=${u.name}${name}${remark}&hasSkuQualificate=${u.hasSkuQualificate}${u.hasOwnProperty('arr')?'&arr=' + JSON.stringify(u.arr):''}${u.hasOwnProperty('oldHasSkuQualificate')?'&oldHasSkuQualificate=' + u.oldHasSkuQualificate:''}`
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.checkFromList()
  },
  checkFromList(){
    let { matchSkuList, select } = this.data;
    if(select==-1){ // 未选
      this.setData({ payState:false})
    }else{//选择了
      let user = select > -1 ? (matchSkuList[select].hasOwnProperty('selectedUser') ? matchSkuList[select].selectedUser : []):[];
      let {matchSkuFormList}=matchSkuList[select];
      let mustAns = matchSkuFormList.length>0&&matchSkuFormList.findIndex((value)=>value.required==1)!=-1; // 表单是否有必填项
      let errUserTitle = ''; // 存用户信息错误提示
      if (user.length > 0) {
        if (matchSkuFormList.length > 0) {
          user.forEach((e, i) => {
            if (e.hasSkuQualificate==0||(e.hasSkuQualificate != 8 && e.hasSkuQualificate != 9 && errUserTitle == ''&&mustAns)){
              errUserTitle = `请检查【${e.name}】表单信息`
            }
          });
        }
      }else{
        errUserTitle = '请选择参赛人员'
      }
      this.setData({ payState: errUserTitle == ''})
    }
  },
  
  getGroupValue(e){
    this.setData({ groupValue: e.detail.value})
  },
  choose(e) {
    let index = e.currentTarget.dataset.index
    this.setData({
      select: index != this.data.select ? index : -1
    })
    let { matchSkuList}=this.data
    if (matchSkuList[index].skuNum==0){
      this.showToast('当前组别参赛人数已满')
    }
  },
  //组别弹窗层显示隐藏
  showview() {
    let old = !this.data.showviewstate
    this.setData({showviewstate: old})
    this.checkFromList()
  },
  //添加参赛人员
  add() {
    let { matchSkuList, select } = this.data
    if (select > -1) {
      if (matchSkuList[select].skuNum==0){
        this.showToast('当前组别参赛人数已满')
        return false;
      }
      if (matchSkuList[select].selectedUser!=null&&matchSkuList[select].selectedUser!=''&&matchSkuList[select].selectedUser!=undefined) {
        wx.navigateTo({
          url: '/pages/participant/index?skuId=' + matchSkuList[select].skuId + '&selecteduser=' + JSON.stringify(matchSkuList[select].selectedUser),
        })
      } else {
        wx.navigateTo({
          url: '/pages/participant/index?skuId=' + matchSkuList[select].skuId,
        })
      }
    } else {
      this.showToast('请选择别组')
    }
  },
  //删除已选人员
  del(e) {
    wx.showModal({
      title: '温馨提示',
      content: '是否移除该该参赛者',
      showCancel: true,//是否显示取消按钮
      cancelText: "取消",//默认是“取消”
      cancelColor: '#000000',//取消文字的颜色
      confirmText: "确定",//默认是“确定”
      confirmColor: '#576B95',//确定文字的颜色
      success:res=> {
        if (res.cancel) {
          //点击取消,默认隐藏弹框
        } else {
          //点击确定
          let { matchSkuList, select } = this.data
          matchSkuList[select].selectedUser.splice(e.currentTarget.dataset.index, 1)
          let selectedUser = 'matchSkuList[' + select + '].selectedUser'
          this.setData({
            [selectedUser]: matchSkuList[select].selectedUser
          })
          this.showToast('已删除')
          //重新计算订单价格
          // this._setCalculate()
        }
      }
    })
  },
  showToast(title, icon = 'none', duration=1500){
    wx.showToast({ title: title, icon: icon, duration: duration})
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})